﻿using Xejen.Communication.Configuration;
using Xejen.Communication.Endpoints;
using Xejen.Communication.Soap.Configuration;
using Xejen.Communication.Soap;
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Text;
using System.Text.Json;
using System.Threading;
using System.Threading.Tasks;
using Xejen.Logger;
using Microsoft.Extensions.Logging;
using Xejen.Communication.Http.Communicator;
using Xejen.Communication.Http;

namespace Xejen.Communication.Soap.Communicator
{
    /// <summary>
    /// 基于soap协议实现的通讯器
    /// </summary>
    /// <creator>marc</creator>
    internal class SoapCommunicator : Communicator<SoapConfig, HeartbeatConfig, SoapAddress>, ICommunicator<SoapConfig, HeartbeatConfig>, ISoapCommunicator
    {
        private readonly ILogger _logger;
        private readonly ILoggerManager _loggerManager;

        /// <inheritdoc cref="IHttpCommunicator"/>
        protected IHttpCommunicator HttpCommunicator { get; }

        /// <inheritdoc/>
        protected override JsonSerializerOptions JsonSerializerOptions => Config.JsonSerializerOptions;

        /// <inheritdoc cref="SoapCommunicator"/>
        /// <param name="httpCommunicator"><inheritdoc cref="IHttpCommunicator" path="/summary"/></param>
        /// <param name="config"><inheritdoc cref="Communicator{TConfig, HeartbeatConfig, TAddress}.Config" path="/summary"/></param>
        /// <param name="loggerManager"><inheritdoc cref="ILoggerManager" path="/summary"/></param>
        public SoapCommunicator(
            IHttpCommunicator httpCommunicator,
            SoapConfig config,
            ILoggerManager loggerManager) : base(config, loggerManager)
        {
            Check.NotNull(httpCommunicator, nameof(httpCommunicator));
            Check.NotNull(config, nameof(config));
            Check.NotNull(loggerManager, nameof(loggerManager));

            Config = config;
            httpCommunicator.Config = config;
            HttpCommunicator = httpCommunicator;
            _loggerManager = loggerManager;
            _logger = loggerManager.CreateLogger<SoapCommunicator>();
        }

        /// <inheritdoc/>
        public virtual async Task<HttpResponse> GetServiceAsync(SoapAddress address, SoapConfig soapConfig = null, int timeout = -1, CancellationToken cancellationToken = default)
        {
            return await HttpCommunicator.GetAsync(address, soapConfig, GetTimeout(timeout), cancellationToken);
        }

        /// <inheritdoc/>
        public virtual async Task<HttpResponse> PostServiceAsync<TInput>(SoapAddress address, TInput input, SoapConfig soapConfig = null, int timeout = -1, CancellationToken cancellationToken = default)
        {
            return await HttpCommunicator.PostAsync(address, input, soapConfig, GetTimeout(timeout), cancellationToken);
        }
    }
}
